import { Card as SemiCard, ButtonGroup, Button } from "@douyinfe/semi-ui";
import { IconPlusCircle, IconRefresh, IconDelete } from "@douyinfe/semi-icons";
import { useEffect, useRef } from "react";
import { useModel } from "umi";
import { useReactive } from "ahooks";
import { Avatar, Card, List, message, Popconfirm, Row, Col, Spin, Space, Select, Modal, Table } from "antd";
import { UserOutlined, ApartmentOutlined, TableOutlined } from "@ant-design/icons";
import { OrganizationGraph } from "@ant-design/graphs";

import useGlobalSetting from "../hooks/globalSetting/useGlobalSetting";
import useDeleteInstitution from "../hooks/institution/useDeleteInstitution";
import useStaff from "../hooks/staff/useStaff";
import useInstitutionDeletePosition from "../hooks/institution/useDeletePosition";

import useInstitutionsByType from "../hooks/institution/useInstitutionsByType";

import AddPosition from "../components/institution/AddPosition";

import AddDepartment from "../components/departments/Add";
import EditDepartmentModle from "../components/departments/Edit";

const oiType = "职能部门";

// 部门设置
const DepartmentsPage = () => {
    const { windowInnerHeight } = useModel("global");

    const { staffs } = useStaff({});

    const { loading, loadInstitutionsByType, institutions } = useInstitutionsByType(oiType);

    const state = useReactive({
        currentInstitution: {},
        currentOperate: "添加新部门",
        showType: "table",
    });

    useEffect(() => {
        if (state.showType === "tree") {
            state.currentInstitution = {};
            state.currentOperate = "添加新部门";
        }
    }, [state.showType]);

    useEffect(() => {
        if (state.currentInstitution.oiUuid) {
            state.currentInstitution = institutions.find((item) => item.oiUuid === state.currentInstitution.oiUuid);
        }
    }, [institutions]);

    const setCurrentInstitution = (record, currentOperate) => {
        state.currentInstitution = record;
        state.currentOperate = currentOperate;
    };

    const cardTitle = (
        <span style={{ lineHeight: "32px", fontSize: 15 }}>
            {state.currentInstitution?.oiName ? state.currentInstitution?.oiName + " - " + state.currentOperate : state.currentOperate}
        </span>
    );

    const cardBodyHeight = windowInnerHeight - 90 - 20 - 48;

    return (
        <div style={{ padding: 10 }}>
            <Row gutter={10}>
                <Col span={18}>
                    <SemiCard
                        title={<span style={{ lineHeight: "32px", fontSize: 15 }}>职能部门</span>}
                        headerStyle={{ padding: "7px 12px" }}
                        headerExtraContent={
                            <Space>
                                <ButtonGroup>
                                    <Button icon={<TableOutlined />} theme={state.showType === "table" ? "solid" : "light"} onClick={() => (state.showType = "table")} />
                                    <Button icon={<ApartmentOutlined />} theme={state.showType === "tree" ? "solid" : "light"} onClick={() => (state.showType = "tree")} />
                                </ButtonGroup>
                                <ButtonGroup>
                                    <Button
                                        icon={<IconPlusCircle />}
                                        title="添加新部门"
                                        onClick={() => {
                                            state.currentInstitution = {};
                                            state.currentOperate = "添加新部门";
                                        }}
                                    />
                                    <Button icon={<IconRefresh />} onClick={loadInstitutionsByType}></Button>
                                </ButtonGroup>
                            </Space>
                        }
                        shadows="always"
                        bordered={false}
                        bodyStyle={{ padding: 0, height: cardBodyHeight, overflow: "hidden", textAlign: "center" }}
                    >
                        <div style={{ width: "100%" }}>
                            {state.showType === "table" && (
                                <InstitutionTable
                                    loading={loading}
                                    institutions={institutions}
                                    setCurrentInstitution={setCurrentInstitution}
                                    cardBodyHeight={cardBodyHeight}
                                    reloadData={loadInstitutionsByType}
                                />
                            )}
                            {state.showType === "tree" && <InstitutionTree institutions={institutions} cardBodyHeight={cardBodyHeight} />}
                        </div>
                    </SemiCard>
                </Col>
                <Col span={6}>
                    <SemiCard
                        title={cardTitle}
                        headerStyle={{ padding: "7px 12px" }}
                        shadows="always"
                        bordered={false}
                        bodyStyle={{ padding: 0, height: cardBodyHeight, overflow: "auto" }}
                        headerExtraContent={<ButtonGroup></ButtonGroup>}
                    >
                        <Space direction="vertical" size={10} style={{ padding: "10px 16px", width: "100%" }}>
                            {!state.currentInstitution?.oiUuid && state.currentOperate === "添加新部门" && (
                                <Card bordered={true} size="small">
                                    <AddDepartment staffs={staffs} reloadData={loadInstitutionsByType} />
                                </Card>
                            )}

                            {state.currentInstitution?.oiUuid && state.currentOperate === "详情" && (
                                <Card bordered={true} size="small">
                                    <EditDepartmentModle staffs={staffs} reloadData={loadInstitutionsByType} department={state.currentInstitution} />
                                </Card>
                            )}

                            {state.currentInstitution?.oiUuid && state.currentOperate === "详情" && (
                                <Card title="在岗人员" bordered={true} size="small" bodyStyle={{ padding: 0 }}>
                                    <InstitutionPositions positions={state.currentInstitution.children} reloadData={loadInstitutionsByType} />
                                </Card>
                            )}

                            {state.currentInstitution?.oiUuid && state.currentOperate === "详情" && (
                                <Card title="添加岗位（从员工）" bordered={true} size="small">
                                    <AddPosition
                                        institutionPositions={state.currentInstitution.children}
                                        reloadData={loadInstitutionsByType}
                                        institution={state.currentInstitution}
                                    />
                                </Card>
                            )}
                        </Space>
                    </SemiCard>
                </Col>
            </Row>
        </div>
    );
};

const InstitutionTable = ({ loading, institutions, setCurrentInstitution, cardBodyHeight, reloadData }) => {
    const { deleteInstitution } = useDeleteInstitution();

    const renderOperate = (_, r, i) => (
        <ButtonGroup>
            <Button theme="borderless" onClick={() => setCurrentInstitution(r, "详情")}>
                详情
            </Button>
            {r.children.length === 0 && (
                <Popconfirm
                    title="确认要删除该机构信息吗？"
                    okButtonProps={{ loading: false }}
                    onConfirm={async () => {
                        let res = await deleteInstitution(r.oiUuid);
                        if (res) {
                            message.success("成功删除机构信息");
                            reloadData();
                        }
                    }}
                >
                    <Button theme="borderless" style={{ color: "#f50" }}>
                        删除
                    </Button>
                </Popconfirm>
            )}
        </ButtonGroup>
    );

    return (
        <Table
            loading={loading}
            bordered
            dataSource={institutions}
            rowKey={"id"}
            pagination={false}
            expandable={{ rowExpandable: false, showExpandColumn: false }}
            scroll={{ y: cardBodyHeight }}
        >
            <Table.Column title="序号" width={70} align="center" render={(_, r, i) => i + 1} />
            <Table.Column title="部门名称" dataIndex={"oiName"} />
            <Table.Column title="部门负责人" dataIndex={"maInfo"} width={140} render={(_, r, i) => _.osName || "-"} />
            <Table.Column title="职责说明" dataIndex={"oiDesc"} />
            <Table.Column title="在岗人数" dataIndex={"children"} align="center" width={100} render={(_, r, i) => _.length || 0} />
            <Table.Column title="创建日期" dataIndex={"crInfo"} width={140} render={(_, r, i) => (_.time ? formatUTCTime(_.time, "YYYY年MM月DD日") : "-")} />
            <Table.Column title="操作" width={140} render={renderOperate} />
        </Table>
    );
};

const InstitutionTree = ({ institutions, cardBodyHeight }) => {
    const { organizationInfo } = useModel("organization.info");
    const { loadGlobalSettings } = useGlobalSetting();

    const state = useReactive({
        treeData: {},
    });

    const loadData = async () => {
        let globalSettings = await loadGlobalSettings();

        const data = {
            id: "root",
            value: {
                name: organizationInfo.fullName,
                title: globalSettings["organization-head"]?.osName || "-",
            },
            children: institutions,
        };

        state.treeData = data;
    };

    useEffect(() => {
        loadData();
    }, [institutions]);

    if (!state.treeData.id) return <></>;

    return (
        <OrganizationGraph
            data={state.treeData}
            height={cardBodyHeight}
            autoFit={false}
            layout={{ direction: "TB" }}
            nodeCfg={{
                autoWidth: true,
                padding: 9,
                style: (node) => {
                    return node.id === "root" ? { fill: "#91d5ff", stroke: "#91d5ff" } : {};
                },
                label: {
                    style: (node, group, type) => {
                        const rootStyles = {
                            title: { fill: "#000" },
                            name: { fill: "#000" },
                        };
                        const styles = {
                            icon: { width: 32, height: 32 },
                            title: { fill: "#000" },
                            name: { fill: "#000" },
                        };
                        if (node.id === "root") return rootStyles[type];
                        return node.value?.type === "成员" ? styles[type] : {};
                    },
                },
            }}
            onReady={(graph) => {
                graph.on("node:click", (evt) => {
                    // console.log(evt);
                });
            }}
        />
    );
};

const InstitutionPositions = ({ positions, reloadData }) => {
    const { deleteInstitutionPosition } = useInstitutionDeletePosition();

    const renderOperate = (_, r, i) => (
        <ButtonGroup>
            <Popconfirm
                title="确认要删除该岗位信息吗？"
                okButtonProps={{ loading: false }}
                onConfirm={async () => {
                    let res = await deleteInstitutionPosition(r.reUuid);
                    if (res) {
                        message.success("成功移除岗位信息");
                        reloadData();
                    }
                }}
            >
                <Button theme="borderless" style={{ color: "#f50" }}>
                    移除
                </Button>
            </Popconfirm>
        </ButtonGroup>
    );

    return (
        <Table bordered={false} dataSource={positions} rowKey={"id"} size="small" pagination={false}>
            <Table.Column title="序号" width={60} align="center" render={(_, r, i) => i + 1} />
            <Table.Column title="姓名" dataIndex={"osName"} />
            <Table.Column title="岗位" dataIndex={"opName"} width={140} />
            <Table.Column title="操作" width={80} render={renderOperate} />
        </Table>
    );
};

export default DepartmentsPage;
